package entjava.poker;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entjava.poker.model.Card;
import entjava.poker.model.Deck;
import entjava.poker.model.Game;
import entjava.poker.model.Player;
import entjava.poker.service.PlayerService;
import entjava.poker.service.SmallBigService;

@WebServlet("/Poker")
public class PokerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	PlayerService playservice = new PlayerService();
	SmallBigService sbs;
//	Deck deck = new Deck();
	Card first, second;
	int count= 1;
	ArrayList<Player> myList;
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = request.getServletContext();
		String userName;

		userName = request.getParameter("userName");
		
		boolean result = playservice.checkInput(userName);	
		
		Game game=(Game)request.getAttribute("game");
		request.getSession().setAttribute("playservice", playservice);

	
		if(result && playservice.getPlayers().size()<10 && game==null){
			String id= (String) request.getSession().getId();	
			
			//check if exist inside the arraylist  if not addUsername
			Player pl = playservice.addUserName(userName, id);   // add to player arraylist		
		
			myList= playservice.getPlayers();
			context.setAttribute("pList", myList);
			
			if(count==1){
			sbs = new SmallBigService(myList);
			count++;
			}
			context.setAttribute("smallbig", sbs);
			
			
		//	request.setAttribute("player", pl);
			request.getSession().setAttribute("player", pl);  
		
			List<String> allnames = playservice.getPlayerList(userName);
			context.setAttribute("playerlist", allnames);
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
			dispatcher.forward(request, response);
			return;
		}else{
			response.sendRedirect("login.jsp");
			return;
		}
	
	}

}
